package com.wingy.test;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SwipeItemClickListener {

    private static ConfigFlie configFlie = new ConfigFlie(true, "");
    private static MenuItem item_day_night = null;
    private RecyclerViewAdpter recyclerViewAdpter;

    LifeDiary lifeDiary = new LifeDiary(null, null);
    //日记列
    private List<LifeDiary> lifeDiaryList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //读入配置文件
        //configFlie = new ConfigFlie(true, "");
        //写出预设配置
        ConfigFlie temp = new ConfigFlie(true, "");
        //configFlie.Saveconfig(getFilesDir().getAbsolutePath(), configFlie);
        if(temp.Readconfig(getFilesDir().getAbsolutePath()) != null) {
            configFlie = temp.Readconfig(getFilesDir().getAbsolutePath());
        }

        //有密码
        if(!("".equals(configFlie.getPWD()))) {
            //showUnlockDialog();
        }

        //从本地读入日记存档
        LifeDiary init = new LifeDiary("", "","");
        lifeDiaryList = lifeDiary.readLifediary(getFilesDir().getAbsolutePath(), configFlie.getPWD());
        lifeDiaryList.add(0, init);
        //非初次使用
        if (lifeDiaryList.size() > 1) {
            TextView welcome;
            welcome = (TextView) findViewById(R.id.first_text_view);
            welcome.setVisibility(View.INVISIBLE);
        }

        SwipeMenuRecyclerView swipeMenuRecyclerView = findViewById(R.id.recycler_view);
        swipeMenuRecyclerView.setSwipeItemClickListener(this);
        swipeMenuRecyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
        swipeMenuRecyclerView.setSwipeMenuItemClickListener(mMenuItemClickListener);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //横向
        //layoutManager.setOrientation(layoutManager.HORIZONTAL);
        //网格布局
        //GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        swipeMenuRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        swipeMenuRecyclerView.setLayoutManager(layoutManager);

        recyclerViewAdpter = new RecyclerViewAdpter(lifeDiaryList);
        swipeMenuRecyclerView.setAdapter(recyclerViewAdpter);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //创建新日记
                Intent intent0 = new Intent(MainActivity.this, EditActivity.class);
                intent0.setAction(EditActivity.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                MainActivity.this.finish();
                //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        item_day_night = navigationView.getMenu().findItem(R.id.nav_share);
        navigationView.setNavigationItemSelectedListener(this);

        //日夜模式
        SharedPreferences sha = getSharedPreferences("name", MODE_PRIVATE);
        //boolean  isNight=sha.getBoolean("night",false);
        if (configFlie.getISNIGHT()) {
            //白天模式
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
            sha.edit().putBoolean("night", false).commit();
            configFlie.setISNIGHT(true);
            item_day_night.setTitle("夜间主题");
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
            sha.edit().putBoolean("night", true).commit();
            configFlie.setISNIGHT(false);
            item_day_night.setTitle("日间主题");
        }
        //recreate();

    }

    @Override
    public void onItemClick(View view, int position) {
        String mid = Long.toString(position-1);

        Intent intent = new Intent(MainActivity.this, EditActivity.class);
        intent.setAction(EditActivity.EDIT_DIARY_ACTION);
        Bundle bundle = new Bundle();
        bundle.putLong("id", position-1);
        intent.putExtras(bundle);
        startActivity(intent);
        MainActivity.this.finish();
        //Toast.makeText(this, "第" + position + "个", Toast.LENGTH_SHORT).show();
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = 160;

            // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
            // 2. 指定具体的高，比如80;
            // 3. WRAP_CONTENT，自身高度，不推荐;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 因为左边要DrawerLayout的侧滑，所以不添加左侧菜单，添加后DrawerLayout将滑不动，但是菜单可以滑动。

            // 只添加Item右侧的菜单。
            {
                SwipeMenuItem closeItem = new SwipeMenuItem(MainActivity.this)
                        .setBackground(R.drawable.red)
                        .setImage(R.drawable.ic_action_delete)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(closeItem); // 添加菜单到左侧。

                SwipeMenuItem shareItem = new SwipeMenuItem(MainActivity.this)
                        .setBackground(R.drawable.purple)
                        .setImage(R.drawable.ic_menu_share)
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(shareItem); // 添加菜单到左侧。
            }
        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            menuBridge.closeMenu();

            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                //Toast.makeText(MainActivity.this, "list第" + adapterPosition + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
                if (menuPosition == 0) {//点击删除按钮
                    lifeDiaryList.remove(adapterPosition);
                    lifeDiary.delLifeDairy(getFilesDir().getAbsolutePath(), adapterPosition-1, configFlie.getPWD());
                    recyclerViewAdpter.notifyItemRemoved(adapterPosition);
                    recreate();
                }else if(menuPosition == 1 ) {//点击分享按钮
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_TEXT, lifeDiaryList.get(adapterPosition).getBody());
                    shareIntent.setType("text/plain");
                    //设置分享列表的标题，并且每次都显示分享列表
                    startActivity(Intent.createChooser(shareIntent, "分享到"));
                }
            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                //Toast.makeText(MainActivity.this, "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            //显示感谢dialog
            showDialog();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        //item_day_night = item;
        if (id == R.id.nav_share) {

            SharedPreferences sha = getSharedPreferences("name", MODE_PRIVATE);
            boolean isNight = sha.getBoolean("night", false);
            if (isNight) {
                //白天模式

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                sha.edit().putBoolean("night", false).commit();
                configFlie.setISNIGHT(true);
                item_day_night.setTitle("夜间主题");
                //写出配置
                configFlie.Saveconfig(getFilesDir().getAbsolutePath(), configFlie);
            } else {

                AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                sha.edit().putBoolean("night", true).commit();
                configFlie.setISNIGHT(false);
                item_day_night.setTitle("日间主题");
                //写出配置
                configFlie.Saveconfig(getFilesDir().getAbsolutePath(), configFlie);
            }
            recreate();
        } else if(id == R.id.nav_pwd) {
            showSettingPWDDialog();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void showDialog(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this);
        normalDialog.setTitle("感谢以下：");
        normalDialog.setMessage("SwipeRecyclerView:\nhttps://github.com/yanzhenjie/SwipeRecyclerView\n\nEncrypt:\nhttps://github.com/GcsSloop/encrypthttps://github.com/GcsSloop/encrypt");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }


    private void showSettingPWDDialog() {
        final AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.setting_password_daialog,null);
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText editText1 =
                                (EditText) dialogView.findViewById(R.id.input_pwd);
                        //旧密码
                        String oldkey = configFlie.getPWD();
                        //设置密码
                        configFlie.setPWD(editText1.getText().toString());
                        //写出配置
                        configFlie.Saveconfig(getFilesDir().getAbsolutePath(),configFlie);
                        //重写日志
                        lifeDiary.rWLifeDairy(getFilesDir().getAbsolutePath(), oldgit AA fserD rdeafswX , configFlie.getPWD());
                        Toast.makeText(MainActivity.this, "设置成功", Toast.LENGTH_SHORT).show();

                    }
                });
        customizeDialog.show();
    }

    private void showUnlockDialog() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.unlock_dialog,null);
        customizeDialog.setTitle("我是一个自定义Dialog");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText edit_text =
                                (EditText) dialogView.findViewById(R.id.edit_text);
                        //密码符合
                        if (!edit_text.getText().toString().equals(configFlie.getPWD())){
                            Toast.makeText(MainActivity.this,
                                    "密码"+edit_text.getText().toString()+"错误",
                                    Toast.LENGTH_SHORT).show();
                            showUnlockDialog();
                        }

                        Toast.makeText(MainActivity.this,
                                "密码"+edit_text.getText().toString()+"正确",
                                Toast.LENGTH_SHORT).show();
                    }
                });
        customizeDialog.show();
    }
}